package com.astro.app;

import org.apache.log4j.Logger;

import com.checkfree.isolutions.persist.PersistLogMessages;
import com.checkfree.isolutions.persist.PersistServer;
import com.checkfree.isolutions.utility.CFiError;
import com.checkfree.isolutions.utility.CFiList;

public class AppBase {

	static final Logger log = Logger.getLogger(AppBase.class);

	/**
	 * Only commit a transaction if one is active on this thread, and it was
	 * started locally.
	 * <p>
	 * If the commit fails, a rollback must be taken. The caller has no way of
	 * explicitly calling for a rollback and therefore this transaction would be
	 * left open barring any subsequent work from ever being committed.
	 * <P>
	 * 
	 * @param localTxn
	 *            indicating whether transaction was started locally
	 * @return boolean indicating if transaction was really committed
	 * @throws CFiError
	 */
	protected boolean commitTransactionIfNeeded(boolean localTxn)
			throws CFiError {
		if (localTxn) {
			try {
				if (PersistServer.transactionIsActive()) {
					PersistServer.commitTransaction();
				}
			} catch (CFiError e) {
				// Yikes! Roll 'er back
				rollbackTransactionIfNeeded(localTxn);

				// Yell
				PersistLogMessages.EXCEPTION_COMMIT_FAILED_ROLLBACK_TAKEN
						.throwError(new CFiList(e.toString()));
			}
		}

		return (localTxn);
	}

	/**
	 * Only rollback a transaction if one is active on this thread, and it was
	 * started locally
	 * 
	 * NOTE: The prefered method of starting a service is to use the
	 * startService to take advantage of the logging on start/cleanup of the
	 * service.
	 * 
	 * @param localTxn
	 *            indicating whether transaction was started locally
	 * @return boolean indicating if transaction was really rolled back
	 */
	protected boolean rollbackTransactionIfNeeded(boolean localTxn) {
		boolean reallyDidIt = false;
		try {
			if (localTxn && PersistServer.transactionIsActive()) {
				PersistServer.rollbackTransaction();
				reallyDidIt = true;
			}
		} catch (CFiError err) {
			// ignore error; we're just trying to rollback cuz of an exception
			// anyway
		}
		return (reallyDidIt);
	}

	/**
	 * Only begin a transaction if one is not already active on this thread.
	 * 
	 * NOTE: The prefered method of starting a service is to use the
	 * startService to take advantage of the logging on start/cleanup of the
	 * service.
	 * 
	 * return boolean indicating if transaction was really started
	 * 
	 * @throws CFiError
	 */
	protected boolean startTransactionIfNeeded() throws CFiError {
		// Ensure the application has activated the persistence layer.
		PersistServer.activateForPersistence();

		// begin a transaction (if required)
		boolean localTransaction = false;
		if (!PersistServer.transactionIsActive()) {
			PersistServer.beginTransaction();
			localTransaction = true;
		}
		return localTransaction;
	}
}
